<template>
  <div class="invoice-auto">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>自动开票设置</h2>
      <el-button type="primary" @click="handleAdd">
        <el-icon><Plus /></el-icon>添加规则
      </el-button>
    </div>

    <!-- 规则列表 -->
    <el-card class="rule-list">
      <el-table
        v-loading="loading"
        :data="ruleList"
        border
        style="width: 100%"
      >
        <el-table-column type="index" width="50" />
        <el-table-column prop="name" label="规则名称" min-width="150" />
        <el-table-column prop="type" label="发票类型" width="150">
          <template #default="{ row }">
            <el-tag :type="row.type === 'special' ? 'success' : 'info'">
              {{ row.type === 'special' ? '增值税专用发票' : '增值税普通发票' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="triggerType" label="触发方式" width="120">
          <template #default="{ row }">
            <el-tag :type="getTriggerTypeTag(row.triggerType)">
              {{ getTriggerTypeLabel(row.triggerType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="condition" label="触发条件" min-width="200" show-overflow-tooltip>
          <template #default="{ row }">
            {{ getConditionLabel(row) }}
          </template>
        </el-table-column>
        <el-table-column prop="templateName" label="使用模板" min-width="150" show-overflow-tooltip />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-switch
              v-model="row.status"
              :active-value="1"
              :inactive-value="0"
              @change="handleStatusChange(row)"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
            <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加/编辑规则对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '添加规则' : '编辑规则'"
      width="600px"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="规则名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入规则名称" />
        </el-form-item>
        <el-form-item label="发票类型" prop="type">
          <el-radio-group v-model="form.type">
            <el-radio label="special">增值税专用发票</el-radio>
            <el-radio label="normal">增值税普通发票</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="触发方式" prop="triggerType">
          <el-select v-model="form.triggerType" placeholder="请选择触发方式">
            <el-option label="订单完成时" value="order_complete" />
            <el-option label="订单支付时" value="order_payment" />
            <el-option label="定时触发" value="scheduled" />
            <el-option label="金额累计" value="amount_accumulate" />
          </el-select>
        </el-form-item>

        <!-- 订单完成时触发条件 -->
        <template v-if="form.triggerType === 'order_complete'">
          <el-form-item label="订单类型" prop="orderTypes">
            <el-select
              v-model="form.orderTypes"
              multiple
              placeholder="请选择订单类型"
            >
              <el-option label="普通订单" value="normal" />
              <el-option label="预约订单" value="appointment" />
              <el-option label="团购订单" value="group" />
            </el-select>
          </el-form-item>
        </template>

        <!-- 订单支付时触发条件 -->
        <template v-if="form.triggerType === 'order_payment'">
          <el-form-item label="支付方式" prop="paymentMethods">
            <el-select
              v-model="form.paymentMethods"
              multiple
              placeholder="请选择支付方式"
            >
              <el-option label="微信支付" value="wechat" />
              <el-option label="支付宝" value="alipay" />
              <el-option label="余额支付" value="balance" />
              <el-option label="现金支付" value="cash" />
            </el-select>
          </el-form-item>
        </template>

        <!-- 定时触发条件 -->
        <template v-if="form.triggerType === 'scheduled'">
          <el-form-item label="触发时间" prop="scheduleTime">
            <el-time-picker
              v-model="form.scheduleTime"
              format="HH:mm"
              placeholder="请选择触发时间"
            />
          </el-form-item>
          <el-form-item label="触发周期" prop="scheduleCycle">
            <el-select v-model="form.scheduleCycle" placeholder="请选择触发周期">
              <el-option label="每天" value="daily" />
              <el-option label="每周" value="weekly" />
              <el-option label="每月" value="monthly" />
            </el-select>
          </el-form-item>
        </template>

        <!-- 金额累计触发条件 -->
        <template v-if="form.triggerType === 'amount_accumulate'">
          <el-form-item label="累计金额" prop="accumulateAmount">
            <el-input-number
              v-model="form.accumulateAmount"
              :min="0"
              :precision="2"
              :step="100"
              placeholder="请输入累计金额"
            />
          </el-form-item>
          <el-form-item label="统计周期" prop="accumulateCycle">
            <el-select v-model="form.accumulateCycle" placeholder="请选择统计周期">
              <el-option label="每天" value="daily" />
              <el-option label="每周" value="weekly" />
              <el-option label="每月" value="monthly" />
            </el-select>
          </el-form-item>
        </template>

        <el-form-item label="使用模板" prop="templateId">
          <el-select
            v-model="form.templateId"
            placeholder="请选择发票模板"
            filterable
          >
            <el-option
              v-for="template in templateList"
              :key="template.id"
              :label="template.name"
              :value="template.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="form.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import {
  getMerchantInvoiceAutoRuleList,
  addMerchantInvoiceAutoRule,
  updateMerchantInvoiceAutoRule,
  deleteMerchantInvoiceAutoRule,
  updateMerchantInvoiceAutoRuleStatus,
  getMerchantInvoiceTemplateList
} from '@/api/merchant'

// 规则列表数据
const loading = ref(false)
const ruleList = ref([])
const templateList = ref([])

// 对话框相关
const dialogVisible = ref(false)
const dialogType = ref('add')
const formRef = ref(null)
const form = reactive({
  id: '',
  name: '',
  type: 'normal',
  triggerType: 'order_complete',
  orderTypes: [],
  paymentMethods: [],
  scheduleTime: null,
  scheduleCycle: 'daily',
  accumulateAmount: 0,
  accumulateCycle: 'daily',
  templateId: '',
  remark: ''
})

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入规则名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择发票类型', trigger: 'change' }
  ],
  triggerType: [
    { required: true, message: '请选择触发方式', trigger: 'change' }
  ],
  orderTypes: [
    { required: true, message: '请选择订单类型', trigger: 'change' }
  ],
  paymentMethods: [
    { required: true, message: '请选择支付方式', trigger: 'change' }
  ],
  scheduleTime: [
    { required: true, message: '请选择触发时间', trigger: 'change' }
  ],
  scheduleCycle: [
    { required: true, message: '请选择触发周期', trigger: 'change' }
  ],
  accumulateAmount: [
    { required: true, message: '请输入累计金额', trigger: 'blur' }
  ],
  accumulateCycle: [
    { required: true, message: '请选择统计周期', trigger: 'change' }
  ],
  templateId: [
    { required: true, message: '请选择发票模板', trigger: 'change' }
  ]
}

// 获取规则列表
const getRuleList = async () => {
  loading.value = true
  try {
    const { data } = await getMerchantInvoiceAutoRuleList()
    ruleList.value = data
  } catch (error) {
    console.error('获取自动开票规则列表失败:', error)
    ElMessage.error('获取自动开票规则列表失败')
  } finally {
    loading.value = false
  }
}

// 获取模板列表
const getTemplateList = async () => {
  try {
    const { data } = await getMerchantInvoiceTemplateList()
    templateList.value = data
  } catch (error) {
    console.error('获取发票模板列表失败:', error)
  }
}

// 添加规则
const handleAdd = () => {
  dialogType.value = 'add'
  Object.keys(form).forEach(key => {
    if (key === 'type') {
      form[key] = 'normal'
    } else if (key === 'triggerType') {
      form[key] = 'order_complete'
    } else if (Array.isArray(form[key])) {
      form[key] = []
    } else {
      form[key] = ''
    }
  })
  dialogVisible.value = true
}

// 编辑规则
const handleEdit = (row) => {
  dialogType.value = 'edit'
  Object.keys(form).forEach(key => {
    form[key] = row[key]
  })
  dialogVisible.value = true
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    if (dialogType.value === 'add') {
      await addMerchantInvoiceAutoRule(form)
      ElMessage.success('添加成功')
    } else {
      await updateMerchantInvoiceAutoRule(form)
      ElMessage.success('更新成功')
    }
    dialogVisible.value = false
    getRuleList()
  } catch (error) {
    console.error('保存自动开票规则失败:', error)
  }
}

// 更新规则状态
const handleStatusChange = async (row) => {
  try {
    await updateMerchantInvoiceAutoRuleStatus({
      id: row.id,
      status: row.status
    })
    ElMessage.success('状态更新成功')
  } catch (error) {
    console.error('更新规则状态失败:', error)
    row.status = row.status === 1 ? 0 : 1
  }
}

// 删除规则
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确认删除该规则吗？', '提示', {
      type: 'warning'
    })
    await deleteMerchantInvoiceAutoRule(row.id)
    ElMessage.success('删除成功')
    getRuleList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除自动开票规则失败:', error)
    }
  }
}

// 获取触发方式标签类型
const getTriggerTypeTag = (type) => {
  const typeMap = {
    order_complete: 'success',
    order_payment: 'primary',
    scheduled: 'warning',
    amount_accumulate: 'info'
  }
  return typeMap[type] || ''
}

// 获取触发方式标签文本
const getTriggerTypeLabel = (type) => {
  const typeMap = {
    order_complete: '订单完成时',
    order_payment: '订单支付时',
    scheduled: '定时触发',
    amount_accumulate: '金额累计'
  }
  return typeMap[type] || type
}

// 获取触发条件文本
const getConditionLabel = (row) => {
  switch (row.triggerType) {
    case 'order_complete':
      return `订单类型：${row.orderTypes.map(type => {
        const typeMap = {
          normal: '普通订单',
          appointment: '预约订单',
          group: '团购订单'
        }
        return typeMap[type] || type
      }).join('、')}`
    case 'order_payment':
      return `支付方式：${row.paymentMethods.map(method => {
        const methodMap = {
          wechat: '微信支付',
          alipay: '支付宝',
          balance: '余额支付',
          cash: '现金支付'
        }
        return methodMap[method] || method
      }).join('、')}`
    case 'scheduled':
      return `每天 ${row.scheduleTime} 触发`
    case 'amount_accumulate':
      return `累计金额达到 ¥${row.accumulateAmount} 时触发`
    default:
      return '-'
  }
}

onMounted(() => {
  getRuleList()
  getTemplateList()
})
</script>

<style lang="scss" scoped>
.invoice-auto {
  padding: 20px;

  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;

    h2 {
      margin: 0;
      font-size: 20px;
      font-weight: 500;
    }
  }

  .rule-list {
    margin-bottom: 20px;
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style> 